package com.leyou.user.interceptors;

import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.user.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
@Slf4j
@EnableConfigurationProperties(JwtProperties.class)
public class AppTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties props;

    //拦截器返回true表示请求放行，返回false表示拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        try {

            //从请求头中，根据header名称获取token
            String token = request.getHeader(props.getApp().getHeaderName());

            //使用公钥解析token
            Payload<AppInfo> infoFromToken = JwtUtils.getInfoFromToken(token, props.getPublicKey(), AppInfo.class);

            //从token的解析结果中获取封装的appInfo
            AppInfo info = infoFromToken.getInfo();

            //获取服务名称
            String serviceName = info.getServiceName();

            //解析获取服务来源可以请求的目标地址
            List<Long> targetList = info.getTargetList();

            //判断当前服务的id是否在目标集合中
            if (!targetList.contains(props.getApp().getId())) {
                response.setStatus(HttpStatus.UNAUTHORIZED.value());//返回状态码401
                log.error("【用户服务】,禁止请求通过，请求来源为:{},请求的目标路径为:{}", serviceName, requestURI);
                return false;//返回false表达的意思就是拦截
            }
            log.info("【用户服务】,允许请求通过，请求来源为:{},请求的目标路径为:{}", serviceName, requestURI);
        } catch (Exception e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());//返回状态码401
            log.error("【用户服务】,禁止请求通过,请求的目标路径为:{}",requestURI);
            return false;
        }
        return true;

    }
}
